package com.vm.activity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.vm.adapter.FoundAdapter;
import com.vm.adapter.MySimpleAdapter;
import com.vm.adapter.PresentAdapter;
import com.vm.adapter.SearchAdapter;
import com.vm.commons.VMConst;
import com.vm.model.ActiveSoft;
import com.vm.model.Soft;
import com.vm.myview.ViewUtils;
import com.vm.utils.JsonUtils;
import com.wwt.app.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 
 * @ProjectName: [WeiMai]
 * @Author: [kent.wang]
 * @CreateDate: [2015年2月2日 上午10:26:56]
 * @Version: [v1.0]
 * 
 */
public class SearchActivity extends Activity {

	protected static final String TAG = "SearchActivity";
	EditText et_appname;
	Button btn_search;
	ImageButton imgbtn_search_back; // 返回按钮

	private RequestQueue mQueue;
	ImageLoader mImageLoader;
	ImageListener listener;
	private List<ActiveSoft> list_hot_app;
	private List<ActiveSoft> list_hot_game;
	ScrollView mScrollView;
	boolean canRequest = false;
	String name;
	int pageNow = 0;
	LinearLayout found_ll_1;
	LinearLayout llayout_hot;
	ViewUtils viewUtils;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_content);

		mQueue = Volley.newRequestQueue(this);

		init();
		viewUtils = new ViewUtils(this);

		list_hot_app = new ArrayList<ActiveSoft>();
		String url = VMConst.REQUEST_URL + "getHotSearchApp";
		JsonArrayRequest json_hot_App = new JsonArrayRequest(url,
				new Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray arg0) {

						for (int i = 0; i < arg0.length(); i++) {
							try {
								if (arg0.length() == 10) {
									canRequest = true;
								}
								
								JSONObject jsonObject = arg0.getJSONObject(i);
								final ActiveSoft soft = JsonUtils.jsonToBean(
										jsonObject, ActiveSoft.class);

								list_hot_app.add(soft);

							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}

						MySimpleAdapter adapter = new MySimpleAdapter(
								SearchActivity.this, list_hot_app);
						GridView gridView = (GridView) findViewById(R.id.gv_app);
						gridView.setOnItemClickListener(gd_listener);
						gridView.setAdapter(adapter);

					}

				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// Log.e(TAG, error.getMessage(), error);
					}
				});

		mQueue.add(json_hot_App);

		list_hot_game = new ArrayList<ActiveSoft>();
		String url2 = VMConst.REQUEST_URL + "getHotSearchGame";

		JsonArrayRequest json_hot_game = new JsonArrayRequest(url2,
				new Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray arg0) {

						for (int i = 0; i < arg0.length(); i++) {
							try {
								JSONObject jsonObject = arg0.getJSONObject(i);
								final ActiveSoft soft = JsonUtils.jsonToBean(
										jsonObject, ActiveSoft.class);

								list_hot_game.add(soft);

							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}

						MySimpleAdapter adapter = new MySimpleAdapter(
								SearchActivity.this, list_hot_game);
						GridView gridView = (GridView) findViewById(R.id.gv_game);
						gridView.setOnItemClickListener(gd_listener);
						gridView.setAdapter(adapter);

					}

				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// Log.e(TAG, error.getMessage(), error);
					}
				});

		mQueue.add(json_hot_game);
	}

	/**
	 * 
	 */
	private void init() {
		mScrollView = (ScrollView) findViewById(R.id.scrollview_list);
		mScrollView.setOnTouchListener(new TouchListenerImpl());
		llayout_hot = (LinearLayout) findViewById(R.id.llayout_hot);

		btn_search = (Button) findViewById(R.id.btn_search);
		btn_search.setOnClickListener(searClickListener);

		imgbtn_search_back = (ImageButton) findViewById(R.id.imgbtn_search_back);
		imgbtn_search_back.setOnClickListener(btn_backListener);
	}

	/**
	 * imgbtn_search_back返回按钮监听
	 */
	OnClickListener btn_backListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Log.i(TAG, "imgbtn_search_back返回按钮监听");
			onBackPressed();

		}
	};

	/**
	 * 返回按钮监听(手机自带返回按钮)
	 */
	@Override
	public void onBackPressed() {
		Log.i(TAG, "返回按钮监听(手机自带返回按钮)");
		super.onBackPressed();
		System.out.println("按下了back键   onBackPressed()");
	}

	public OnClickListener searClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			llayout_hot.setVisibility(View.GONE);
			et_appname = (EditText) findViewById(R.id.et_appname);
			name = et_appname.getText().toString();

			list_hot_app = new ArrayList<ActiveSoft>();
			try {
				name = URLEncoder.encode(name, "UTF-8");
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			found_ll_1 = (LinearLayout) findViewById(R.id.found_ll_1);
			String url = VMConst.REQUEST_URL + "searchApp?keyword=" + name;
			JsonArrayRequest searchArrayRequest = new JsonArrayRequest(url,
					new Listener<JSONArray>() {
						@Override
						public void onResponse(JSONArray arg0) {

							found_ll_1.removeAllViews();
							pageNow = 0;
							for (int i = 0; i < arg0.length(); i++) {
								try {
									JSONObject jsonObject = arg0
											.getJSONObject(i);
									final Soft soft = JsonUtils
											.jsonToBean(jsonObject,
													Soft.class);
									
									ActiveSoft activeSoft = new ActiveSoft();
									activeSoft.setSoftId(soft.getId());
									activeSoft.setName(soft.getName());
									activeSoft.setImageUrl(soft.getImageUrl());
									activeSoft.setApkUrl(soft.getApkUrl());
									activeSoft.setSize(soft.getSize());
									activeSoft.setStar(soft.getStar());
									activeSoft.setPackageName(soft.getPackageName());
									activeSoft.setDownload(soft.getDownload());
									activeSoft.setVersion(soft.getVersion());

									found_ll_1.addView(viewUtils.dyAddView(i,
											activeSoft,1));

								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}

						}

					}, new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError error) {
							// Log.e(TAG, error.getMessage(), error);
						}
					});

			mQueue.add(searchArrayRequest);

		}
	};

	OnItemClickListener gd_listener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			Intent intent = new Intent(SearchActivity.this,
					DetailActivity.class);
			TextView textView = (TextView) view.findViewById(R.id.tv_softName);
			String softId = textView.getTag().toString();
			intent.putExtra("softId", softId);
			startActivityForResult(intent, 10);

		}
	};

	private class TouchListenerImpl implements OnTouchListener {
		@Override
		public boolean onTouch(View view, MotionEvent motionEvent) {
			switch (motionEvent.getAction()) {
			case MotionEvent.ACTION_DOWN:

				break;
			case MotionEvent.ACTION_MOVE:
				int scrollY = view.getScrollY();
				int height = view.getHeight();
				int scrollViewMeasuredHeight = mScrollView.getChildAt(0)
						.getMeasuredHeight();
				if (scrollY == 0) {
					System.out.println("滑动到了顶端 view.getScrollY()=" + scrollY);
				}
				if ((scrollY + height) == scrollViewMeasuredHeight) {

					if (canRequest) {
						canRequest = false;
						System.out.print("canRequest:" + canRequest);
						pageNow += 1;
						System.out.print("pageNow:" + pageNow);
						String url = VMConst.REQUEST_URL + "searchApp?keyword="
								+ name + "&pageNow=" + pageNow;
						JsonArrayRequest searchArrayRequest = new JsonArrayRequest(
								url, new Listener<JSONArray>() {
									@Override
									public void onResponse(JSONArray arg0) {
										Log.i(TAG, "json长度:" + arg0.length());

										for (int i = 0; i < arg0.length(); i++) {
											try {
												JSONObject jsonObject = arg0
														.getJSONObject(i);
												final ActiveSoft activeSoft = JsonUtils
														.jsonToBean(jsonObject,
																ActiveSoft.class);

												found_ll_1.addView(viewUtils
														.dyAddView(i, activeSoft,1));

											} catch (JSONException e) {
												// TODO Auto-generated catch
												// block
												e.printStackTrace();
											}
										}

										canRequest = true;

									}

								}, new Response.ErrorListener() {
									@Override
									public void onErrorResponse(
											VolleyError error) {
										// Log.e(TAG, error.getMessage(),
										// error);
									}
								});

						mQueue.add(searchArrayRequest);

						// System.out.println("滑动到了底部 scrollY=" + scrollY);
						// System.out.println("滑动到了底部 height=" + height);
						// System.out.println("滑动到了底部 scrollViewMeasuredHeight="
						// + scrollViewMeasuredHeight);
					}

				}
				break;

			default:
				break;
			}
			return false;
		}

	};

}
